﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using System.Xml.Linq;
using System.Text;
using System.ServiceModel.Syndication;
using System.IO;
using System.Net;

namespace IndyMosaic.Models.Syndication
{
    public class Feed
    {

        public static SyndicationFeed GetFeed(string title, string description, IEnumerable<ISyndicationItem> entries, string entryPermalinkBaseUrl, System.Web.Mvc.UrlHelper urlHelper)
        {
            SyndicationFeed feed = new SyndicationFeed(GetItems(entries, entryPermalinkBaseUrl.ToString(), urlHelper));
            feed.Title = new TextSyndicationContent(title);
            feed.Description = new TextSyndicationContent(description);
            feed.Links.Add(new SyndicationLink(new Uri(entryPermalinkBaseUrl.Replace("Details/{0}", ""))));
            
            return feed;
        }

        private static IEnumerable<SyndicationItem> GetItems(IEnumerable<ISyndicationItem> entries, string entryPermalinkBaseUrl, System.Web.Mvc.UrlHelper urlHelper)
        {
            foreach (ISyndicationItem entry in entries)
            {
                string content = entry.Content;
                if (!string.IsNullOrWhiteSpace(content))
                {
                    entry.Content.Replace(entry.MoreTag, "");
                }
                SyndicationItem si = new SyndicationItem(entry.Title, content, new Uri(string.Format(entryPermalinkBaseUrl, entry.ID)));
                if (!string.IsNullOrWhiteSpace(entry.GetEnclosureURL(urlHelper)))
                {
                    Uri uri = new Uri(entry.GetEnclosureURL(urlHelper));
                    si.Links.Add(SyndicationLink.CreateMediaEnclosureLink(uri, "audio/mp3", (entry.EnclosureLength > 0)? entry.EnclosureLength : 30));
                    si.Id = uri.ToString();
                    
                }
                
                yield return si;
            }
        }
    }
}
